'use client';

import React, { useState, useEffect } from 'react';
import { Upload, Button, message } from 'antd';
import { PlusOutlined, UploadOutlined } from '@ant-design/icons';
import type { UploadFile, UploadProps } from 'antd';
import type { RcFile, UploadRequestOption as RcCustomRequestOptions } from 'rc-upload/lib/interface';
import { FileMetaType } from '@/types/file';

// 支持的 value 类型
type ImageValue = string | { picImg?: string; picImgUrl?: string; url?: string; fileUrl?: string; };

interface UploadComponentProps {
  value?: ImageValue | ImageValue[];
  onChange?: (fileList: string[] | FileMetaType[]) => void;
  maxCount?: number;
  accept?: string;
  listType?: 'text' | 'picture' | 'picture-card';
  multiple?: boolean;
  disabled?: boolean;
  placeholder?: string;
  customUpload?: (file: File) => Promise<FileMetaType>;
}

const UploadComponent: React.FC<UploadComponentProps> = ({
  value,
  onChange,
  maxCount = 1,
  accept,
  listType = 'picture-card',
  multiple = false,
  disabled = false,
  placeholder = '点击上传图片',
  customUpload,
}) => {
  const [fileList, setFileList] = useState<UploadFile[]>([]);

  // 提取图片 URL 的辅助函数
  const extractImageUrl = (item: ImageValue): string | null => {
    if (!item) return null;
    
    if (typeof item === 'string') {
      return item;
    }
    
    if (typeof item === 'object') {
      // 优先使用完整的 URL
      return item.picImgUrl || item.url || item.picImg || item.fileUrl || null;
    }
    
    return null;
  };

  // 处理 value 的初始化和更新
  useEffect(() => {
    if (!value) {
      setFileList([]);
      return;
    }

    // 将 value 统一转换为数组
    const items = Array.isArray(value) ? value : [value];
    
    const newFileList = items
      .map((item, index) => {
        const url = extractImageUrl(item);
        if (!url) return null;
        
        return {
          uid: `${index}`,
          name: `image-${index}`,
          status: 'done' as const,
          url,
        };
      })
      .filter(Boolean) as UploadFile[];

    setFileList(newFileList);
  }, [value]);

  const handleChange: UploadProps['onChange'] = ({ fileList: newFileList }) => {
    setFileList(newFileList);
    
    // 提取已上传成功的文件URL
    const urls = newFileList
      .filter(file => file.status === 'done')
      .map(file => file.url || file.response?.url)
      .filter(Boolean) as string[];
    
    onChange?.(urls);
  };

  const handlePreview = async (file: UploadFile) => {
    if (!file.url && !file.preview) {
      file.preview = await getBase64(file.originFileObj as File);
    }
    
    // 这里可以实现预览功能，比如打开模态框
    message.info('预览功能');
  };

  const beforeUpload = (file: File) => {
    const isImage = file.type.startsWith('image/');
    if (accept && accept.includes('image') && !isImage) {
      message.error('只能上传图片文件!');
      return false;
    }

    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isLt2M) {
      message.error('文件大小不能超过 2MB!');
      return false;
    }

    return true;
  };

  const customRequest = async (options: RcCustomRequestOptions<any>) => {
    const { file, onSuccess, onError } = options;
    
    try {
      if (customUpload) {
        // 使用自定义上传函数
        const result = await customUpload(file as File);
        onSuccess?.(result);
      } else {
        // 模拟上传
        setTimeout(() => {
          try {
            // 模拟返回URL
            const mockUrl = URL.createObjectURL(file as File);
            
            onSuccess?.({
              url: mockUrl,
              name: (file as File).name,
            });
          } catch (error) {
            onError?.(error as Error);
          }
        }, 1000);
      }
    } catch (error) {
      onError?.(error as Error);
    }
  };

  const uploadButton = (
    <div>
      <PlusOutlined />
      <div style={{ marginTop: 8 }}>{placeholder}</div>
    </div>
  );

  if (listType === 'text') {
    return (
      <Upload
        fileList={fileList}
        onChange={handleChange}
        beforeUpload={beforeUpload}
        customRequest={customRequest}
        maxCount={maxCount}
        multiple={multiple}
        disabled={disabled}
        accept={accept}
      >
        <Button icon={<UploadOutlined />} disabled={disabled}>
          {placeholder}
        </Button>
      </Upload>
    );
  }

  return (
    <Upload
      listType={listType}
      fileList={fileList}
      onChange={handleChange}
      onPreview={handlePreview}
      beforeUpload={beforeUpload}
      customRequest={customRequest}
      maxCount={maxCount}
      multiple={multiple}
      disabled={disabled}
      accept={accept}
    >
      {fileList.length >= maxCount ? null : uploadButton}
    </Upload>
  );
};

// 获取文件base64编码
const getBase64 = (file: File): Promise<string> =>
  new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => resolve(reader.result as string);
    reader.onerror = error => reject(error);
  });

export default UploadComponent; 